package org.cy.shixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cy.shixun.dto.UserUpdateDto;
import org.cy.shixun.entity.Users;
import org.cy.shixun.mapper.UsersMapper;
import org.cy.shixun.service.UsersService;
import org.cy.shixun.vo.R;
import org.cy.shixun.vo.UserReg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author TrainingL
 * @since 2023-06-29
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 验证用户名是否重复
     *
     * @return {@link String }
     */
    @Override
    public String validate(String account) {
        LambdaQueryWrapper<Users>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getAccount,account);
        Integer count = usersMapper.selectCount(queryWrapper);
        if(count>0){
            return "用户名重复";
        }
        else{
            return "用户名正确";
        }
    }


    @Override
    public Integer login(Users users) {
        LambdaQueryWrapper<Users>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getAccount,users.getAccount()).eq(Users::getPassword,users.getPassword());
        Integer count = usersMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public String reg(UserReg userReg) {
        if(!userReg.getPassword().equals(userReg.getPassword1())){
            return "两次密码不一致";
        }
        LambdaQueryWrapper<Users>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getAccount,userReg.getUsername());
        Integer count = usersMapper.selectCount(queryWrapper);
        if(count>0){
            return "用户名重复";
        }
        Users users = new Users();
        users.setAccount(userReg.getUsername());
        users.setPassword(userReg.getPassword());
        usersMapper.insert(users);
        return "注册成功";
    }

    @Override
    public R update(UserUpdateDto userUpdateDto) {
        //查询旧密码是否正确
        String oldPassword = userUpdateDto.getOldPassword();
        String account = userUpdateDto.getAccount();
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getAccount,account);
        Users users = usersMapper.selectOne(queryWrapper);
        if(!users.getPassword().equals(oldPassword)){
            return R.error("旧密码错误");
        }

        users.setPassword(userUpdateDto.getNewPassword());
        int i = usersMapper.updateById(users);
        if(i>0){
            return R.success("修改成功");
        }else{
            return R.error("未知错误");
        }
    }

}
